package com.shushan.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;

import com.shushan.util.StringTools;


/**
 * @ClassName: CountdownTextView
 * @Desciption: 倒计时自定义TextView
 * @author: yichaohua
 * @date: 2018-08-04
 */
public class CountdownTextView extends android.support.v7.widget.AppCompatTextView {

    private static final String TAG = "CountdownTextView";


    private int time = 0;//倒计时秒
    private boolean run = true; // 是否启动了

    @SuppressLint("NewApi")
    private Handler handler = new Handler(Looper.getMainLooper()) {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    if (run) {
                        countDownTime();
                    }
                    break;
                default:
                    break;
            }

        }
    };

    public CountdownTextView(Context context) {
        super(context);
    }

    public CountdownTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CountdownTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();

        Log.i(TAG,"onDetachedFromWindow()");

        // 在控件被销毁时移除消息
        handler.removeMessages(0);
    }

    @SuppressLint("NewApi")
    public void setTimes(int mT) {
        // 标示已经启动
        time = mT;

        if (time > 0) {
            run = true;
            handler.removeMessages(0);
            handler.sendEmptyMessage(0);
        } else {
            CountdownTextView.this.setText("00:00");
        }
    }

    public void stop() {
        run = false;
    }

    private void countDownTime() {
        int mTime = time;
        if (mTime > 0) {
            CountdownTextView.this.setText(StringTools.formatTime(mTime));
            handler.sendEmptyMessageDelayed(0, 1000);
            time--;
        }
    }

    public int getTime() {
        return time;
    }

    public void setTime(int time) {
        this.time = time;
    }
}




